import com.proalias.animation.TweenManager;
/**
 * @author Alias Cummins
 */
class com.proalias.animation.tween.Tween {
	
	private var $target:Object;
	private var $time:Number;
	private var $duration:Number;
	private var $startValues:Object;
	private var $end:Number;
	private var $preCalc:Boolean;
	private var $preCalcObj:Object;
	private var $easingFunction:Function;
	private var $properties:Object;
	
	public var execute:Function;
	
	public function Tween(target:Object,properties:Object,easing:String,duration:Number) {
		$target = target;
		$time = 0;
		$duration = int(duration);
		$properties = properties;
		var e:Array = easing.split(".");
		$easingFunction = TweenManager.instance.easingLib[e[0]][e[1]];
		execute = executeRealTime;
	}
	
	public function set preCalculate(val:Boolean){
		$preCalc = val;
		if ($startValues == undefined){
			$startValues = new Object();
			for (var i in $properties){
				$startValues[i] = $target[i];
			}
		}
		if (val==true){
			var func:Function = $easingFunction;
			$preCalcObj = new Object();
			for (var i in $properties){
				$preCalcObj[i] = new Array();
				for (var j:Number = 0;j<$duration;j++){
					var b:Number = $startValues[i];
					var c = $properties[i] - b; 
					var d = $duration;
					$preCalcObj[i][j] = func(j, b, c, d);
				}
			}
			execute = executePreCalc;
		}else{
			execute = executeRealTime;
		}
	}
	
	private function executeRealTime():Boolean{
		//trace("Tween.executeRealTime()");
		var func:Function = $easingFunction;
		if ($startValues == undefined){
			$startValues = new Object();
			for (var i in $properties){
				$startValues[i] = $target[i];
			}
		}
		
		if ($time < $duration){
			for (var i in $properties){
				var b:Number = $startValues[i];
				var c = $properties[i] - b;
				var d = $duration;
				$target[i] = func($time, b, c, d);
			}
			$time++;
			return true;
		}else{
			for (var i in $properties){
				$target[i] = $properties[i];
			}
			execute = null;	
			return false;
		}
		
	}
	
	private function executePreCalc():Boolean{
		//trace("Tween.executePreCalc()");
		if ($time < $duration){
			for (var i in $properties){
				$target[i] = $preCalcObj[i][$time];
			}
			$time++;
			return true;
		}else{
			for (var i in $properties){
				$target[i] = $properties[i];
			}
			return false;
		}
		return true;
	}
	
}